package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import com.hmall.trade.service.impl.OrderServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.LocalTime;

/**
 * 订单延迟消息监听
 * 检测订单支付状态
 * 超时取消订单
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class OrderDelayMessageListener {
    private final IOrderService orderService;
    private final PayClient payClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.DELAY_ORDER_QUEUE_NAME,durable = "true"),
            exchange = @Exchange(value = MqConstants.DELAY_EXCHANGE_NAME,delayed = "true"),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void listenOrdreDelayMessage(Long orderId){
        log.info("=======>"+LocalTime.now()+"订单监听到延迟消息，订单号："+orderId );
        //1、查询订单
        Order order = orderService.getById(orderId);
        //2、检测订单状态，判断是否已支付
        if (order == null || order.getStatus() != 1){
            return ;
        }
        log.info("本地查找发现订单未支付，开始查找支付订单是否支付");
        //3、未支付，需要查询支付流水状态
        PayOrderDTO payOrder = payClient.queryPayOrderByBizOrderNo(orderId);
        //4、判断是否支付
        if (payOrder != null && payOrder.getStatus() == 3){
            log.info("支付订单已支付，修改订单状态为已支付");
            //4.1、已支付，标记订单状态为已支付
            orderService.markOrderPaySuccess(orderId);
        }else {
            log.info("订单超时未支付，取消订单，恢复库存");
            //4.2、TODO 未支付，取消订单，恢复库存
            orderService.cancelOrder(orderId);
        }
    }
}
